<template>
	<view class="order-list">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-icon" @click="goBack">
				<image src="/static/index/returnIcon.png" mode="widthFix" class="back-icon-box"></image>
			</view>
			<view class="title">{{title}}</view>
		</view>

		<view class="filter-bar">
			<view class="filter-item" :class="{ active: !activeLeft }" @click="handleFilter(1)">
				<view class="filter-item-content">
					<text>{{orderValue}}</text>
					<image src="/static/index/groups.png" mode="widthFix" class="active-line-img">
					</image>
				</view>
			</view>
			<view class="filter-item" :class="{ active: !activeRight }" @click="handleFilter(2)">
				<view class="filter-item-content">
					<text>订单时间</text>
					<image src="/static/index/groups.png" mode="widthFix" class="active-line-img">
					</image>
				</view>
			</view>

		</view>
		<view class="filter-T" v-show="activeLeft">
			<view class="filter-T-item" :class="{ active: index == query.status }" v-for="(item,index) in orderType"
				:key="item.id" @click="setType(item.id)">
				<text>{{ item.name }}</text>
			</view>
		</view>
		<view class="order-items">
			<view v-for="(item, index) in orderList" :key="index" class="order-item" @click="viewDetail(item.id)">
				<view class="order-item-header">
					<view class="status" :class="item.status == 2 ? 'completed' : 'pending'">
						{{ getStatus(item.status)}}
					</view>
					<view class="detail-link">
						详情 >
					</view>
				</view>
				<view class="order-info">
					<view class="order-id">订单号：{{ item.id }}</view>
					<!-- <view class="time">柜机名称：{{ item.institutionName||'--' }}</view> -->
					<view class="time">下单时间：{{ item.orderTime||'--' }}</view>
					<view class="time" v-if="item.takeOutTime">取药时间：{{ item.takeOutTime||'--' }}</view>
					<view class="amount">订单金额：¥{{ item.amount ||0}}</view>
					<view class="phone">{{ formatPhoneNumber(item.phoneNumber) }}</view>
					<!-- <view class="method">取药方式：{{ getorderType(item.takeOutType)}}</view> -->
					<view class="method">取药方式：{{ item.takeOutType == 1?'骑手取药':(item.takeOutType == 2?'店员自取':'客户自取')}}
					</view>
				</view>
			</view>
		</view>
		<!-- 无搜索结果 -->
		<view class="empty-result" v-if="orderList.length == 0">
			<image src="/static/images/empty-search.png" mode="aspectFit" class="empty-icon"></image>
			<view class="empty-text">暂无订单</view>
		</view>
		<wu-calendar mode="range" ref="calendar" :rangeSameDay="true" @confirm="confirmDate" :endDate="maxDate"
			:monthShowCurrentMonth="false" slideSwitchMode="none" :clearDate="false" :insert="false"></wu-calendar>
		<uv-load-more :status="status" line v-if="orderList.length > 0" />
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		useUserStore
	} from "@/stores/user.js"
	import {
		getorderList,
		getDictList
	} from "@/api/index.js"
	import {
		onLoad,
		onPullDownRefresh,
		onReachBottom,
		onShow
	} from '@dcloudio/uni-app'
	import {
		timeToDate
	} from "@/utils/mothed.js"

	const userInfo = useUserStore()
	const activeLeft = ref(false)
	const activeRight = ref(false)
	const dataList = ref([])
	const typeList = ref([])
	const calendar = ref(null)
	const defaultDate = ref(null)
	const orderValue = ref('全部订单')

	// 格式化日期
	const formatDate = (date) => {
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		return `${year}-${month}-${day}`
	}

	// 获取默认日期范围（结束日期为当天）
	const defaultRangeDate = ref([
		'', // 开始日期默认为空
		formatDate(new Date()) // 结束日期默认为当天
	])

	// 在函数定义之后再初始化这些值
	const maxDate = ref(formatDate(new Date()))

	const orderType = ref([{
			id: 0,
			name: '全部'
		},
		{
			id: 1,
			name: '已下单'
		},
		{
			id: 2,
			name: '已完成'
		},
		{
			id: 3,
			name: '异常'
		},
		{
			id: 4,
			name: '已取消'
		}
	])

	const query = ref({
		status: 0,
		beginOrderTime: '',
		endOrderTime: '',
		pageNum: 1,
		pageSize: 10,
		cabinetId: ''
	})

	const showCalendar = ref(false)
	const status = ref('loadmore')
	const orderList = ref([])
	const total = ref(0)
	const title = ref('')

	// 处理筛选
	const handleFilter = (filter) => {
		if (filter == 1) {
			activeLeft.value = !activeLeft.value
			activeRight.value = false // 关闭另一个筛选项
		} else if (filter== 2) {
			activeRight.value = !activeRight.value
			if (calendar.value) {
				activeLeft.value = false // 关闭另一个筛选项
				calendar.value.open()
			} else {
				calendar.value.close()
			}
		}
	}

	onLoad((e) => {
		query.value.status = e.status == 3 ? e.status : 0
		if (e.status == 2 || e.status == 3) {
			const res = timeToDate(new Date(), 'yyyy-mm-dd')
			query.value.beginOrderTime = res
			query.value.endOrderTime = res
		} else {
			query.value.beginOrderTime = ''
			query.value.endOrderTime = ''
		}
		query.value.cabinetId = e.id
		title.value = e.name || '订单列表'
	})
	const dictList = () => {
		getDictList('mc_take_out_type').then(res => {
			typeList.value = res.data
		})
	}
	const getorderType = (id) => {
		const found = typeList.value.filter((item) => item.dictValue == id)[0]
		return found ? found.dictLabel : '-'
	}
	const getOrderList = () => {
		status.value = 'loading'
		query.value.status = query.value.status == 0 ? '' : query.value.status
		query.value.beginOrderTime = query.value.beginOrderTime ? query.value.beginOrderTime + ' 00:00:00' : ''
		query.value.endOrderTime = query.value.endOrderTime ? query.value.endOrderTime + ' 23:59:59' : ''
		getorderList(query.value).then(res => {
			if (res.code === 200) {
				orderList.value = query.value.pageNum === 1 ? res.rows : orderList.value.concat(res.rows)
				total.value = res.total
			}
		}).finally(() => {
			status.value = orderList.value.length >= total.value ? 'nomore' : 'loadmore'
			uni.stopPullDownRefresh()
		})
	}
	const setType = (id) => {
		query.value.status = id
		orderValue.value = orderType.value.find(item => item.id == id)?.name || '全部订单'
		orderValue.value = query.value.status != 0 ? orderValue.value : '全部订单'
		getOrderList()
	}

	const viewDetail = (orderId) => {
		// 跳转到订单详情页
		uni.navigateTo({
			url: `/pages/order/detail?id=${orderId}`
		})
	}

	onShow(() => {
		getOrderList()
		dictList()
		defaultDate.value = formatDate(new Date())
	})

	const goBack = () => {
		uni.navigateBack()
	}

	const confirmDate = (e) => {
		console.log(e.range, '---------------')
		if (e.range && e.range.after) {
			query.value.beginOrderTime = e.range.before
			query.value.endOrderTime = e.range.after ? e.range.after : e.range.before
			getOrderList()
		} else {
			query.value.beginOrderTime = ''
			query.value.endOrderTime = ""
			getOrderList()
		}
		activeRight.value = false
	}

	// 下拉刷新
	onPullDownRefresh(() => {
		query.value.pageNum = 1
		getOrderList()
	})

	// 上拉加载更多
	onReachBottom(() => {
		if (orderList.value.length < total.value) {
			query.value.pageNum++
			getOrderList()
		}
	})

	// 处理手机号码中间4位隐藏
	const formatPhoneNumber = (phone) => {
		if (!phone) return ''
		return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
	}

	const getStatus = (val) => {
		if (val == 2) {
			return '已取出'
		} else {
			return '未取出'
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .order-list .filter-bar .filter-item {
		width: 50%;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.empty-result {
		padding-top: 200rpx;
		text-align: center;

		.empty-icon {
			width: 180rpx;
			height: 180rpx;
			margin-bottom: 16rpx;
		}

		.empty-text {
			font-size: 26rpx;
			color: #999;
		}
	}

	.filter-T {
		display: flex;
		align-items: center;
		justify-content: space-evenly;
		padding: 0;
		margin-bottom: 20rpx;
		background: #fff;
		height: 140rpx;
		width: 94.5%;
		margin: 0 auto;
		position: fixed;
		z-index: 1000;
		left: 2.8%;
		top: 18%;
		border-bottom: 1rpx solid #f3f2f2;

		.filter-T-item {
			width: 12%;
			text-align: center;
			font-size: 26rpx;
			color: #9CA3AF;
			background-color: #F3F3F3;
			padding: 12rpx;
			border-radius: 10rpx;
		}

		.filter-T-item.active {
			background-color: #E5F0F9;
			color: #3B82F6;
		}
	}

	.order-list {
		min-height: 100vh;
		background: #C0E5F8;
		margin-bottom: 40rpx;
		overflow: auto;


		.header {
			height: 252rpx;
			background: #C0E5F8;
			display: flex;
			align-items: center;
			padding: 50rpx 30rpx 0;
			position: relative;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 100;
			line-height: 228rpx;

			.back-icon {
				.back-icon-box {
					width: 16rpx;
					height: 16rpx;
				}
			}

			.title {
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
			}

			.search-icon {
				position: absolute;
				right: 30rpx;

				.search-icon-box {
					width: 32rpx;
					height: 36rpx;
				}
			}
		}

		.filter-bar {
			display: flex;
			margin: 40rpx auto 0;
			width: 84%;
			margin-top: 20rpx;
			overflow: hidden;
			position: fixed;
			top: 207rpx;
			left: 0;
			right: 0;
			z-index: 100;
			background: #fff;
			padding: 20rpx 40rpx;
			border-top-left-radius: 60rpx;
			border-top-right-radius: 60rpx;

			.filter-item {
				flex: 1;
				font-size: 28rpx;
				color: #000;
				position: relative;

				.filter-item-content {
					display: flex;
					align-items: center;
					position: relative;
					margin-left: 80rpx;

					text {
						font-size: 30rpx;
					}

					.active-line-img {
						width: 28rpx;
						height: 28rpx;
						margin-left: 8rpx;
						transform: rotate(180deg);
						transition: transform 0.5s ease;
					}
				}

				&.active {

					.active-line-img {
						transform: rotate(0deg);
					}
				}
			}
		}

		.order-items {
			margin: 0 20rpx;
			background: #fff;
			padding: 20rpx;
			border: 1rpx solid #f3f2f2;
			border-bottom-right-radius: 60rpx;
			border-bottom-left-radius: 60rpx;
			margin-top: 300rpx;

			.order-item {
				background: #fff;
				border-radius: 16rpx;
				padding: 30rpx 30rpx 24rpx;
				margin-bottom: 20rpx;
				border: 1rpx solid #f3f2f2;

				.order-item-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;
				}

				.status {
					width: 88rpx;
					height: 34rpx;
					text-align: center;
					padding: 6rpx 10rpx;
					line-height: 34rpx;
					border-radius: 5px;
					font-size: 28rpx;

					&.completed {
						background: #F0FDF4;
						color: #16A34A;
					}

					&.pending {
						color: #F97316;
						background: #FFF7ED;
					}
				}

				.order-info {
					view {
						font-size: 27rpx;
						color: #6B7280;
						margin-bottom: 12rpx;
						line-height: 1.3;

						&:last-child {
							margin-bottom: 0;
						}
					}

					.order-id {
						color: #333;
						font-weight: 600;
					}
				}

				.detail-link {
					color: #1890ff;
					font-size: 28rpx;
				}
			}
		}
	}
</style>